import ala from 'ala'
import admin from 'admin'

export async function view (id, fatherId) {
  var para = {
    id: id,
    fatherId: fatherId,
    type: ala.urlType()
  }

  var response = await ala.httpGet('Api/RelationTree/GetView', para)
  if (!response.relation) {
    ala.error('数据获取错误')
  }
  if (response.relation.status === 1) {
    response.relation.isEnable = true
  } else {
    response.relation.isEnable = false
  }
  return response
}


// 编辑
export async function edit (array, row) {
  if (!row) {
    ala.error('没有选择编辑的行')
  }
  row.type = ala.urlType()
  if (row.isEnable === true) {
    row.status = 1
  } else {
    row.status = 2
  }
  var result = await admin.relationSave(row)
  if (result) {
    ala.toast(row.name + '修改成功')
  } else {
    return array
  }
  if (row.id > 0) {
    // 非新增数据不需要更新页面
    return array
  }
  if (row.fatherId <= 0) {
    array.forEach(r => {
      if (r.id === 0) {
        r.id = result.id
        r.modifiedTime = result.modifiedTime
        r.createTime = result.createTime
      }
    })
  } else {
    array.forEach(r => {
      if (r.id === row.fatherId && r.children) {
        r.children.forEach(c => {
          if (c.id === 0) {
            c.id = result.id
            r.modifiedTime = result.modifiedTime
            c.createTime = result.createTime
          }
        })
      }
    })
  }
  return array
}
